<?php
/**
 * EditController.php
 *
 * @copyright  2023 beikeshop.com - All Rights Reserved
 * @link       https://beikeshop.com
 * @author     TL <mengwb@guangda.work>
 * @created    2023-05-29 20:22:54
 * @modified   2023-05-29 20:22:54
 */

namespace Beike\Seller\Http\Controllers;

use Beike\Repositories\CountryRepo;
use Beike\Seller\Http\Requests\EditPasswordRequest;
use Beike\Seller\Http\Requests\EditRequest;
use Beike\Seller\Repositories\SellerGroupRepo;
use Beike\Seller\Repositories\SellerRepo;
use Beike\Seller\Services\UserService;
use function current_seller_user;

class EditController extends Controller
{
    protected string $defaultRoute = 'edit.index';

    /**
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    public function index()
    {
        $seller = current_seller_user()->seller;
        $data   = [
            'seller'        => $seller,
            'seller_groups' => SellerGroupRepo::list(),
            'countries'     => CountryRepo::listEnabled(),
        ];

        return view('seller::pages.seller.edit', $data);
    }

    /**
     * @param EditRequest $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(EditRequest $request)
    {
        $user = SellerRepo::update(current_seller_user()->seller, $request->all());

        return redirect()->to($this->getRedirect())->with('success', trans('common.updated_success'));
    }

    /**
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    public function password()
    {
        return view('seller::pages.seller.password', []);
    }

    /**
     * @param EditPasswordRequest $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function savePassword(EditPasswordRequest $request)
    {
        try {
            UserService::changePassword($request->all());
        } catch (\Exception $e) {
            return redirect()->to(seller_route('edit.password'))->with('error', $e->getMessage());
        }

        return redirect()->to(seller_route('edit.password'))->with('success', trans('seller::edit.password_success'));
    }
}
